package com.kanshu.ksgb.fastread.doudou.common.util;

import android.content.Context;
import android.os.Environment;

import com.bumptech.glide.disklrucache.DiskLruCache;
import com.kanshu.ksgb.fastread.doudou.app.Xutils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.Type;
import java.util.List;

/**
 * 硬盘缓存工具类
 * Created by wanchunyang on 2017\5\3 0003.
 */
public class DiskLruCacheUtils {

    private static final String DIR_NAME = "diskCache";
    private static final int MAX_COUNT = 500 * 1024 * 1024;
    private static final int DEFAULT_APP_VERSION = 1;
    /**
     * The default valueCount when open DiskLruCache.
     */
    private static final int DEFAULT_VALUE_COUNT = 1;

    private static  DiskLruCache sDiskLruCache;

    private static String sCacheDir;

    private static DiskLruCache getDiskLruCache() {
        if (sDiskLruCache != null) {
            return sDiskLruCache;
        }
        try {
            sDiskLruCache = DiskLruCache.open(
                    getDiskCacheDir(Xutils.getContext(), DIR_NAME),
                    DEFAULT_APP_VERSION,
                    DEFAULT_VALUE_COUNT,
                    MAX_COUNT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sDiskLruCache;
    }

    public static File getDiskCacheDir(Context context, String uniqueName) {
        if (context == null) {
            return null;
        }
        String cachePath = null;
        try {
            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                    || !Environment.isExternalStorageRemovable()) {
                File cacheDir = context.getExternalCacheDir();
                if (cacheDir != null) {
                    cachePath = cacheDir.getPath();
                } else {
                    cachePath = Environment.getExternalStorageDirectory().getPath();
                }
            } else {
                cachePath = context.getCacheDir().getPath();
            }
        } catch (Exception e) {
            e.printStackTrace();
            cachePath = context.getCacheDir().getPath();
        }
        sCacheDir = cachePath + File.separator + uniqueName;
        return new File(sCacheDir);
    }

    public static void put(String key, Object object) {
        String s = JsonUtils.bean2JsonByFastJson(object);
        put(key, s);
    }

    public static void put(final String key, final Object object, boolean async) {
        if (async) {
            ThreadPoolUtil.getInstance().addTask(new Runnable() {
                @Override
                public void run() {
                    put(key, object);
                }
            });
        } else {
            put(key, object);
        }
    }

    public static void put(String key, String value) {
        getDiskLruCache();
        if (sDiskLruCache == null) {
            return ;
        }
        DiskLruCache.Editor edit = null;
        BufferedWriter bw = null;
        try
        {
            key = MD5Util.md5(key);
            edit = sDiskLruCache.edit(key);
            if (edit == null) return;
            OutputStream os = new FileOutputStream(edit.getFile(0));
            bw = new BufferedWriter(new OutputStreamWriter(os));
            bw.write(value);
            edit.commit();//write CLEAN
        } catch (IOException e)
        {
            e.printStackTrace();
            try
            {
                if (edit == null) {
                    return;
                }
                //s
                edit.abort();//write REMOVE
            } catch (Exception e1)
            {
                e1.printStackTrace();
            }
        } finally
        {
            try
            {
                if (bw != null)
                    bw.close();
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

    public static <T> T get(String key, Class<T> clazz) {
        getDiskLruCache();
        if (sDiskLruCache == null) {
            return null;
        }
        T t = null;
        try {
            DiskLruCache.Value value = sDiskLruCache.get(MD5Util.md5(key));
            if (value != null) {
                String string = value.getString(0);
                t = JsonUtils.json2BeanByFastJson(string, clazz);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return t;
    }

    public static <T> T get(String key, Type type) {
        getDiskLruCache();
        T t = null;
        if (sDiskLruCache == null) {
            return null;
        }
        try {
            DiskLruCache.Value value = sDiskLruCache.get(MD5Util.md5(key));
            if (value != null) {
                String string = value.getString(0);
                t = JsonUtils.json2Bean(string, type);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return t;
    }
    public static <T> List<T> getArray(String key, Class<T> beanClass) {
        getDiskLruCache();
        if (sDiskLruCache == null) {
            return null;
        }
        try {
            DiskLruCache.Value value = sDiskLruCache.get(MD5Util.md5(key));
            if (value != null) {
                String string = value.getString(0);
                return JsonUtils.json2ArrayByFastJson(string, beanClass);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 清除缓存数据
     */
    public static void clear() {
        if (sCacheDir == null) {
            return;
        }
        File file = new File(sCacheDir);
        if (!file.exists() || !file.isDirectory()) {
            return;
        }
        File[] files = file.listFiles();
        if (files != null) {
            for (File f : files) {
                f.delete();
            }
        }
    }
}
